<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Js常用数组 | 李世龙</title><meta name="keywords" content="javaScript"><meta name="author" content="lee"><meta name="copyright" content="lee"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="JavaScript数组方法改变原数组1.arr.push()​    向数组末尾添加一个或多个元素,返回新数组长度,原数组改变 12arr&#x3D;[1,2,3];arr.push(4,5,6)&#x2F;&#x2F;返回数组长度6  arr&#x3D;[1,2,3,4,5,6]  2.arr.pop()删除并返回数组的最后一个元素，若该数组为空，则返回undefined。原数组改变 12arr&#x3D;[1,2,3];arr.pop()&#x2F;">
<meta property="og:type" content="article">
<meta property="og:title" content="Js常用数组">
<meta property="og:url" content="http://blog.cai2.wang/2022/08/23/Js%E5%B8%B8%E7%94%A8%E6%95%B0%E7%BB%84/index.html">
<meta property="og:site_name" content="李世龙">
<meta property="og:description" content="JavaScript数组方法改变原数组1.arr.push()​    向数组末尾添加一个或多个元素,返回新数组长度,原数组改变 12arr&#x3D;[1,2,3];arr.push(4,5,6)&#x2F;&#x2F;返回数组长度6  arr&#x3D;[1,2,3,4,5,6]  2.arr.pop()删除并返回数组的最后一个元素，若该数组为空，则返回undefined。原数组改变 12arr&#x3D;[1,2,3];arr.pop()&#x2F;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/undraw_dev_productivity_umsq.png">
<meta property="article:published_time" content="2022-08-23T13:02:27.000Z">
<meta property="article:modified_time" content="2022-08-23T13:05:28.016Z">
<meta property="article:author" content="lee">
<meta property="article:tag" content="javaScript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/undraw_dev_productivity_umsq.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/avatar.jpg"><link rel="canonical" href="http://blog.cai2.wang/2022/08/23/Js%E5%B8%B8%E7%94%A8%E6%95%B0%E7%BB%84/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Js常用数组',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-08-23 21:05:28'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/iconfont.css"><link rel="stylesheet" href="/css/index.min.css"><link rel="stylesheet" href="/css/bg.css"><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/avatar.jpg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">13</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">9</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/video/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li><li><a class="site-page child" href="/love/"><i class="fa-fw fa fa-heartbeat"></i><span> 心动</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/my/"><i class="fa-fw fas fa-ad"></i><span> 我的</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-seedling"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">李世龙</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/video/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li><li><a class="site-page child" href="/love/"><i class="fa-fw fa fa-heartbeat"></i><span> 心动</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/my/"><i class="fa-fw fas fa-ad"></i><span> 我的</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-seedling"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">Js常用数组</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-08-23T13:02:27.000Z" title="发表于 2022-08-23 21:02:27">2022-08-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-08-23T13:05:28.016Z" title="更新于 2022-08-23 21:05:28">2022-08-23</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Js常用数组"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="JavaScript数组方法"><a href="#JavaScript数组方法" class="headerlink" title="JavaScript数组方法"></a>JavaScript数组方法</h1><h2 id="改变原数组"><a href="#改变原数组" class="headerlink" title="改变原数组"></a>改变原数组</h2><h4 id="1-arr-push"><a href="#1-arr-push" class="headerlink" title="1.arr.push()"></a>1.arr.push()</h4><p>​    向数组末尾添加一个或多个元素,返回新数组长度,<strong>原数组改变</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line">arr.push(<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>)<span class="comment">//返回数组长度6  arr=[1,2,3,4,5,6]</span></span><br></pre></td></tr></table></figure>

<h4 id="2-arr-pop"><a href="#2-arr-pop" class="headerlink" title="2.arr.pop()"></a>2.arr.pop()</h4><p>删除并返回数组的最后一个元素，若该数组为空，则返回undefined。<strong>原数组改变</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line">arr.pop()<span class="comment">//返回末尾的3  arr=[1,2]</span></span><br></pre></td></tr></table></figure>

<h4 id="3-arr-shift"><a href="#3-arr-shift" class="headerlink" title="3.arr.shift()"></a>3.arr.shift()</h4><p>删除并返回第一个元素,若该数组为空，则返回undefined。<strong>原数组改变</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line">arr.shift()<span class="comment">//返回删除的开头1  arr=[2,3]</span></span><br></pre></td></tr></table></figure>

<h4 id="4-arr-unshift"><a href="#4-arr-unshift" class="headerlink" title="4.arr.unshift(*)"></a>4.arr.unshift(*)</h4><p>向数组首位添加元素,返回新的数组长度。<strong>原数组改变</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr= [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line">arr.unshift(<span class="number">0</span>)<span class="comment">//返回长度4 arr=[0,1,2,3]</span></span><br></pre></td></tr></table></figure>

<h4 id="5-arr-reverse"><a href="#5-arr-reverse" class="headerlink" title="5.arr.reverse()"></a>5.arr.reverse()</h4><p>将数组倒转,<strong>直接改变原数组</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr=[1,2,3];</span><br><span class="line">arr.reverse();//arr变成[1,2,3]</span><br></pre></td></tr></table></figure>

<h4 id="6-sort"><a href="#6-sort" class="headerlink" title="6.sort()"></a>6.sort()</h4><p>对数组排序,<strong>直接改变原数组</strong> </p>
<p>没有参数，默认升序排列；</p>
<p> 参数为function, (a,b)=&gt;b-a 为降序排列 ()=&gt;Math.random()-0.5 简单的乱序 </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">arr=[<span class="number">1</span>,<span class="number">3</span>,<span class="number">2</span>];</span><br><span class="line">arr.sort()<span class="comment">//arr变成[1,2,3]</span></span><br><span class="line">arr.sort(<span class="function"><span class="keyword">function</span>(<span class="params">a,b</span>)=&gt;</span>&#123;</span><br><span class="line">	retrun b-a<span class="comment">//desc</span></span><br><span class="line">&#125;)</span><br><span class="line">arr.sort(<span class="function">()=&gt;</span><span class="built_in">Math</span>.random()-<span class="number">0.5</span>)<span class="comment">//乱序不准确 不同浏览器sort的排序方式有问题</span></span><br></pre></td></tr></table></figure>

<h4 id="7-splice-startIndex-length-…item-删，增，替换数组元素，"><a href="#7-splice-startIndex-length-…item-删，增，替换数组元素，" class="headerlink" title="7.splice(startIndex,length,…item) 删，增，替换数组元素，"></a>7.splice(startIndex,length,…item) 删，增，替换数组元素，</h4><p><strong>返回被删除数组，无删除则不返回 改变原数组</strong></p>
<p>length 为0时，在下标为 startIndex 位置添加 item<br>length 不为0时，存在 item 时，从下标为 startIndex 开始删除 length 项，并添加 item,没有不添</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]</span><br><span class="line">arr.splice(<span class="number">0</span>,<span class="number">1</span>,<span class="number">5</span>)<span class="comment">//从0号位删除长度1 再添加一个5</span></span><br><span class="line">arr<span class="comment">//2,3,5</span></span><br></pre></td></tr></table></figure>

<h3 id="原数组不改变"><a href="#原数组不改变" class="headerlink" title="原数组不改变"></a><span style='color:red'>原数组不改变</span></h3><h4 id="8-arr-concat-arr1-arr2…-，"><a href="#8-arr-concat-arr1-arr2…-，" class="headerlink" title="8.arr.concat(arr1,arr2…)，"></a>8.arr.concat(arr1,arr2…)，</h4><p>合并两个或多个数组，生成一个新的数组。<span style='color:red;font-family:字体;'>原数组不改变</span></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">arr3.concat([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>],[<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>])<span class="comment">//返回新的数组[1,2,3,4,5,6] 但原数组arr3还是默认</span></span><br></pre></td></tr></table></figure>

<h4 id="9-arr-join"><a href="#9-arr-join" class="headerlink" title="9.arr.join()"></a>9.arr.join()</h4><p>将数组的每一项用指定字符连接形成一个字符串。默认连接字符为 “,” 逗号。<span style='color:red;font-family:字体;'>原数组不改变</span></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>];</span><br><span class="line"><span class="keyword">let</span> str1 = arr.join()	 <span class="comment">//str1:&#x27;1,2,3,4,5&#x27; 默认&#x27;,&#x27;</span></span><br><span class="line"><span class="keyword">let</span> str2 = arr.join(<span class="string">&#x27;-&#x27;</span>) <span class="comment">//str2:&#x27;1-2-3-4-5&#x27;</span></span><br></pre></td></tr></table></figure>

<h4 id="10-arr-slice"><a href="#10-arr-slice" class="headerlink" title="10.arr.slice()"></a>10.arr.slice()</h4><p>slice(startIndex,endIndex)，返回选定元素 <span style='color:red;font-family:字体;'>原数组不改变</span></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>];</span><br><span class="line"><span class="keyword">let</span> newArr = arr.slice(<span class="number">0</span>,<span class="number">2</span>)<span class="comment">//newArr:1,2 左闭右开!!</span></span><br></pre></td></tr></table></figure>

<h4 id="11-arr-forEach-function"><a href="#11-arr-forEach-function" class="headerlink" title="11.arr.forEach(function)"></a>11.arr.forEach(function)</h4><p>循环, 返回值undefined <span style='color:red;font-family:字体;'>原数组不改变</span></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">arr=[&#123;<span class="attr">a</span>:<span class="number">1</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">2</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">3</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">4</span>&#125;]</span><br><span class="line">arr.forEach((item,key)=&#123;</span><br><span class="line">	item.a<span class="comment">//1,2,3,4</span></span><br><span class="line">	arr[key]<span class="comment">//1,2,3,4</span></span><br><span class="line">	key<span class="comment">//0,1,2,3</span></span><br><span class="line">	!!!想修改数据!!!不能改item,改arr[key]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h4 id="12-arr-filter-function-：过滤器"><a href="#12-arr-filter-function-：过滤器" class="headerlink" title="12.arr.filter(function)：过滤器"></a>12.arr.filter(function)：过滤器</h4><p>过滤操作数组,返回新数组<span style='color:red;font-family:字体;'>原数组不改变</span></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">arr=[&#123;<span class="attr">a</span>:<span class="number">1</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">2</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">3</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">4</span>&#125;]</span><br><span class="line"><span class="keyword">let</span> newArr = arr.filter(<span class="function"><span class="params">item</span>=&gt;</span>item.a&gt;<span class="number">1</span>)</span><br><span class="line">newArr<span class="comment">//[&#123;a:3&#125;,&#123;a:4&#125;]</span></span><br></pre></td></tr></table></figure>

<h4 id="13-arr-reduce-function-可以计算累加"><a href="#13-arr-reduce-function-可以计算累加" class="headerlink" title="13.arr.reduce(function) 可以计算累加"></a>13.arr.reduce(function) 可以计算累加</h4><p>返回递归数值,如累加值,<span style='color:red;font-family:字体;'>原数组不改变</span></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">arr = [&#123;<span class="attr">a</span>:<span class="number">1</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">2</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">3</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">4</span>&#125;]</span><br><span class="line"><span class="keyword">let</span> num = arr.reduce(<span class="function">(<span class="params">pre,next</span>)=&gt;</span>&#123; <span class="comment">//参数可以选填index表示当前元素的索引, 可选填arr参数代表原数组</span></span><br><span class="line">    <span class="keyword">return</span> pre+next.a</span><br><span class="line">&#125;,init)<span class="comment">//若提供 init 值，则起始索引为- 0，否则起始索引为1；</span></span><br></pre></td></tr></table></figure>

<h4 id="14-arr-indexOf-lastIndexOf"><a href="#14-arr-indexOf-lastIndexOf" class="headerlink" title="14.arr.indexOf()/lastIndexOf()"></a>14.arr.indexOf()/lastIndexOf()</h4><p>indexOf()检测当前值在数组中第一次出现的位置索引,没有返回-1 <span style='color:red;font-family:字体;'>原数组不改变</span></p>
<p>lastindexOf()检测当前值在数组中<strong>最后一次</strong>出现的位置索引,没有返回-1 <span style='color:red;font-family:字体;'>原数组不改变</span> (从后往前找)</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">arr.indexOf(item,start) item:查找的元素 start:字符串中开始检索的位置(可不写)。</span><br><span class="line">arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br><span class="line">arr.indexOf(<span class="number">2</span>)<span class="comment">//返回下标1</span></span><br></pre></td></tr></table></figure>

<h4 id="15-includes"><a href="#15-includes" class="headerlink" title="15.includes()"></a>15.includes()</h4><p>判断一个数组是否包含一个指定的值,返回布尔值  <span style='color:red;font-family:字体;'>原数组不改变</span></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr=[1,2,3,4]</span><br><span class="line">arr.includes(2)</span><br></pre></td></tr></table></figure>

<h4 id="16-arr-every-function-，"><a href="#16-arr-every-function-，" class="headerlink" title="16.arr.every(function)，"></a>16.arr.every(function)，</h4><p>对数组中的每一项进行判断，若都符合则返回true，否则返回false。  <span style='color:red;font-family:字体;'>原数组不改变</span></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">arr = [&#123;<span class="attr">a</span>:<span class="number">1</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">2</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">3</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">4</span>&#125;]</span><br><span class="line"><span class="keyword">let</span> asd=arr.every(<span class="function"><span class="params">item</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> item.a&gt;<span class="number">1</span> <span class="comment">//第一个对象不符合 有一个不符合就返回false </span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h4 id="17-Array-some-function-，"><a href="#17-Array-some-function-，" class="headerlink" title="17.Array.some(function)，"></a>17.Array.some(function)，</h4><p>对数组中的每一项进行判断，若都不符合则返回false，否则返回true。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">arr = [&#123;<span class="attr">a</span>:<span class="number">1</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">2</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">3</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">4</span>&#125;]</span><br><span class="line"><span class="keyword">let</span> asd=arr.every(<span class="function"><span class="params">item</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> item.a==<span class="number">4</span> <span class="comment">//最后一个对象符合 有一个符合就返回true</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>18.Arr.find/findIndex//找item和item.id</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">lee</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.cai2.wang/2022/08/23/Js%E5%B8%B8%E7%94%A8%E6%95%B0%E7%BB%84/">http://blog.cai2.wang/2022/08/23/Js常用数组/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.cai2.wang" target="_blank">李世龙</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/javaScript/">javaScript</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/undraw_dev_productivity_umsq.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/08/24/Promis-Async-await-Loop/"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/undraw_pair_programming_njlp.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Promis_Async_await_Loop</div></div></a></div><div class="next-post pull-right"><a href="/2022/05/16/Done/Git/"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/undraw_web_development_w2vv.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">常用Git命令</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2021/12/01/Done/JavaScript/" title="javaScript"><img class="cover" src="https://cdn.jsdelivr.net/gh/Cai2w/cdn/img/undraw_Freelancer_re_irh4.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-01</div><div class="title">javaScript</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95"><span class="toc-number">1.</span> <span class="toc-text">JavaScript数组方法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%B9%E5%8F%98%E5%8E%9F%E6%95%B0%E7%BB%84"><span class="toc-number">1.1.</span> <span class="toc-text">改变原数组</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-arr-push"><span class="toc-number">1.1.0.1.</span> <span class="toc-text">1.arr.push()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-arr-pop"><span class="toc-number">1.1.0.2.</span> <span class="toc-text">2.arr.pop()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-arr-shift"><span class="toc-number">1.1.0.3.</span> <span class="toc-text">3.arr.shift()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-arr-unshift"><span class="toc-number">1.1.0.4.</span> <span class="toc-text">4.arr.unshift(*)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5-arr-reverse"><span class="toc-number">1.1.0.5.</span> <span class="toc-text">5.arr.reverse()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6-sort"><span class="toc-number">1.1.0.6.</span> <span class="toc-text">6.sort()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#7-splice-startIndex-length-%E2%80%A6item-%E5%88%A0%EF%BC%8C%E5%A2%9E%EF%BC%8C%E6%9B%BF%E6%8D%A2%E6%95%B0%E7%BB%84%E5%85%83%E7%B4%A0%EF%BC%8C"><span class="toc-number">1.1.0.7.</span> <span class="toc-text">7.splice(startIndex,length,…item) 删，增，替换数组元素，</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%9F%E6%95%B0%E7%BB%84%E4%B8%8D%E6%94%B9%E5%8F%98"><span class="toc-number">1.1.1.</span> <span class="toc-text">原数组不改变</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#8-arr-concat-arr1-arr2%E2%80%A6-%EF%BC%8C"><span class="toc-number">1.1.1.1.</span> <span class="toc-text">8.arr.concat(arr1,arr2…)，</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#9-arr-join"><span class="toc-number">1.1.1.2.</span> <span class="toc-text">9.arr.join()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#10-arr-slice"><span class="toc-number">1.1.1.3.</span> <span class="toc-text">10.arr.slice()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#11-arr-forEach-function"><span class="toc-number">1.1.1.4.</span> <span class="toc-text">11.arr.forEach(function)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#12-arr-filter-function-%EF%BC%9A%E8%BF%87%E6%BB%A4%E5%99%A8"><span class="toc-number">1.1.1.5.</span> <span class="toc-text">12.arr.filter(function)：过滤器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#13-arr-reduce-function-%E5%8F%AF%E4%BB%A5%E8%AE%A1%E7%AE%97%E7%B4%AF%E5%8A%A0"><span class="toc-number">1.1.1.6.</span> <span class="toc-text">13.arr.reduce(function) 可以计算累加</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#14-arr-indexOf-lastIndexOf"><span class="toc-number">1.1.1.7.</span> <span class="toc-text">14.arr.indexOf()&#x2F;lastIndexOf()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#15-includes"><span class="toc-number">1.1.1.8.</span> <span class="toc-text">15.includes()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#16-arr-every-function-%EF%BC%8C"><span class="toc-number">1.1.1.9.</span> <span class="toc-text">16.arr.every(function)，</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#17-Array-some-function-%EF%BC%8C"><span class="toc-number">1.1.1.10.</span> <span class="toc-text">17.Array.some(function)，</span></a></li></ol></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2022 By lee</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">这是footer</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (true){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      true && mermaid.init()
    })
  }
}</script></div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>